package com.ximu.user.filter;

import com.ximu.common_utlis.jwt.JwtUtil;

import com.ximu.redis.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


/**
 * @projectName: java
 * @package: com.ximu.filter
 * @className: JwtTokenFilter
 * @author: ximu
 * @description: null
 * @date: 2022/5/16 8:48
 * @version: 1.0
 */
@Component
public class JwtTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取token
        //获取请求头为token的数据
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            //return:响应时还会执行一次过滤器，所以需要return
            return;
        }


        //解析token
        //定义userId
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        //从redis查询用户信息
        String redisKey = "hongsai:login"+userId;
        Object cacheObject = redisUtil.getCacheObject(redisKey);
        if (Objects.isNull(cacheObject)){
            throw new RuntimeException("用户未登录");
        }

        //存入SecurityContextHolder
        //这里需要传入三个参数，已认证为true，这样后面的就不会拦截了
        //第三个数据获取权限信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(cacheObject,null,null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        //放行
        filterChain.doFilter(request,response);

    }
}
